#include "Base.h"
#include <unistd.h>
#include <errno.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <libCommon.h>


ssize_t             /* Read "n" bytes from a descriptor */
readn(int fd, void *ptr, size_t n)
{
    size_t       nleft;
    ssize_t      nread;

    nleft = n;
    while (nleft > 0) {
        if ((nread = read(fd, ptr, nleft)) < 0) {
            if (nleft == n)
                return(-1); /* error, return -1 */
            else
                break;      /* error, return amount read so far */
        } else if (nread == 0) {
            break;          /* EOF */
        }
        nleft -= nread;
        ptr += nread;
    }
    return(n - nleft);      /* return >= 0 */
}

ssize_t             /* Write "n" bytes to a descriptor */
writen(int fd, const void *ptr, size_t n)
{
    size_t      nleft;
    ssize_t     nwritten;

    nleft = n;
    while (nleft > 0) {
        if ((nwritten = write(fd, ptr, nleft)) < 0) {
            if (nleft == n)
                return(-1); /* error, return -1 */
            else
                break;      /* error, return amount written so far */
        } else if (nwritten == 0) {
            break;
        }
        nleft -= nwritten;
        ptr   += nwritten;
    }
    return(n - nleft);      /* return >= 0 */
}

 /*
  * "Timed" read - timout specifies the # of seconds to wait before
  * giving up (5th argument to select controls how long to wait for
  * data to be readable).  Returns # of bytes read or -1 on error.
  * This function is useful when reading from a socket or a pipe.
 * LOCKING: none.
 */
ssize_t
tread(int fd, void *buf, size_t nbytes, unsigned int sec,unsigned int usec)
{
    int             nfds,errno;
    fd_set          readfds;
    struct timeval  tv;

    tv.tv_sec = sec;
    tv.tv_usec = usec;
    FD_ZERO(&readfds);
    FD_SET(fd, &readfds);
    nfds = select(fd+1, &readfds, NULL, NULL, &tv);
    if (nfds <= 0) {
        if (nfds == 0)
            errno = nfds;
        return(-1);
    }
    return(read(fd, buf, nbytes));
}


/* = 0 sucess, file exist
     = -1, fail    file isn't exist*/
int chk_file_exist(char *path)
{
	struct stat fstat;
	if(-1 == stat(path, &fstat))
	{
		if(errno == ENOENT)  //path isnot exist
			return FALSE;
	}
    if( !S_ISREG(fstat.st_mode) ) {
        return FALSE;   //path is not a regular file..
    }
    return TRUE;
}

